﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ornament.MemberShip;
using Ornament.MemberShip.Module.Presenters;
using Ornament.MemberShip.Module.Views;

public partial class Admin_MemberAdmin_Controls_OrgAssign : UserControl, IOrgAssignView
{
    public Org SelectedOrg
    {
        get { return Presenter.GetSelectedOrg(); }
    }

    public string ClientClickFunctionMethod
    {
        get
        {
            if (ViewState["ClientClickFunctionMethod"] == null)
                return null;
            return ViewState["ClientClickFunctionMethod"].ToString();
        }
        set { ViewState["ClientClickFunctionMethod"] = value; }
    }

    #region IOrgAssignView Members

    public OrgAssignPresenter Presenter { get; set; }

    public Guid SelectedId
    {
        get { return new Guid(orgTreeView.SelectedValue); }
    }

    public void BindTreeview(IList<Org> orgs)
    {
        TreeNode root = orgTreeView.Nodes[0];
        orgTreeView.Nodes[0].ChildNodes.Clear();
        OrgAddToTreeView(orgs, root);
    }

    public void AssignOrgTo(User user)
    {
        Presenter.AssignTo(user);
    }

    #endregion

    private void OrgAddToTreeView(IEnumerable<Org> orgs, TreeNode parent)
    {
        foreach (Org org in orgs)
        {
            var result = new TreeNode {Text = org.Name, Value = org.Id.ToString()};
            if (ClientClickFunctionMethod != null)
            {
                result.NavigateUrl = "javascript:" + ClientClickFunctionMethod + "('" + result.Value + "','" +
                                     result.Text + "')";
            }
            parent.ChildNodes.Add(result);
            ReadOnlyCollection<Org> childOrgs = org.GetAllChilds();
            if (childOrgs.Count != 0)
            {
                OrgAddToTreeView(childOrgs, result);
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Presenter = new OrgAssignPresenter(this);
        if (!IsPostBack)
        {
            Presenter.InitilizeView();
        }
        Presenter.ViewLoad();
    }
}